package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Service
public class GreenhouseService extends LogicService<GreenhouseDao, Greenhouse, Long> {
    
    @PersistenceContext
    private EntityManager entityManager;
    
    public GreenhouseService(@Autowired GreenhouseDao dao) {
        super(dao);
    }
    
    /**
     * 查询单个大棚信息（包含设备信息）
     */
    public Greenhouse getGreenhouseInfo(Long id) throws Exception {
        return dao.findById(id)
                .orElseThrow(() -> new Exception("大棚不存在"));
    }
    
    /**
     * 更新大棚信息
     */
    public Greenhouse updateGreenhouse(Greenhouse greenhouse) throws Exception {
        // 获取原有大棚信息
        Greenhouse existingGreenhouse = dao.findById(greenhouse.getId())
                .orElseThrow(() -> new Exception("大棚不存在"));
        
        // 验证必填字段
        if (greenhouse.getName() == null || greenhouse.getName().trim().isEmpty()) {
            throw new Exception("大棚名称不能为空");
        }
        if (greenhouse.getAddress() == null || greenhouse.getAddress().trim().isEmpty()) {
            throw new Exception("大棚地址不能为空");
        }
        if (greenhouse.getArea() == null || greenhouse.getArea() <= 0) {
            throw new Exception("大棚面积必须大于0");
        }
        
        // 保留原有的逻辑删除字段值
        greenhouse.setIsDeleted(existingGreenhouse.getIsDeleted());
        greenhouse.setDeletedTime(existingGreenhouse.getDeletedTime());
        
        return dao.save(greenhouse);
    }
} 